package com.cm.kits.oss;

import com.cm.kits.HttpTool;
import com.cm.kits.JacksonKits;
import com.cm.kits.YamlKits;
import lombok.Data;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

/**
 * Oss 工具
 *
 * @author LWang 2023.02.02
 * @since 1.0.0
 */
public final class OssKits {
    private OssKits() {
    }

    @Data
    public static class OssConfig {
        private String url;
    }

    @Data
    public static class OssResult {
        private int code;
        private String data;
        private String msg;
        private String traceId;
    }

    private final static HttpTool HTTP_TOOL;

    private final static OssConfig CONFIG;

    static {
        try {
            HTTP_TOOL = new HttpTool();
            CONFIG = YamlKits.load("oss.yaml", OssConfig.class);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将文件上传到 OSS
     *
     * @param file 要上传的文件
     * @return OSS 资源 ID
     */
    public static String upload(File file) throws IOException, InterruptedException {
        var url = "%s/res/support/api/oss/upload".formatted(CONFIG.url);
        var result = HTTP_TOOL.post(url, null, null, new ArrayList<>() {{
            this.add(Pair.of("file", file));
        }}, null, null);
        if (!result.getKey().equals(HttpStatus.SC_OK)) {
            throw new RuntimeException("上传资源文件异常，服务无响应。");
        }
        var ossResult = JacksonKits.toBean(result.getValue(), OssResult.class);
        assert ossResult != null;
        if (ossResult.getCode() != HttpStatus.SC_OK) {
            throw new RuntimeException("上传资源文件异常，" + ossResult.getMsg() + "," + ossResult.getTraceId());
        }
        return ossResult.data;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        upload(new File("d:/result.jpg"));
    }
}
